﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using TPCN.DAL;
using TPCN.Common;
using System.Text.RegularExpressions;
using TPCN.Commons;

namespace TPCN.Admincp
{
    public partial class Hang : System.Web.UI.Page
    {
        private static string HangID = String.Empty;
        private static string Solanmua = "0";
        private static double giabanle = 0;
        private static double giabanbuon = 0;
        private static double giathitruong = 0;
        private static List<HangObj> source;
        private static List<DanhmucObj> categories;
        private static HangObj obj;

        private const string UPDATE = "Cập nhật";
        private const string INSERT = "Thêm";
        private const string CMD_EDIT = "cmdEdit";
        private const string CMD_DELETE = "cmdDelete";


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();
                LoadDonvitinh();
                InitForm();
            }
        }

        protected void InitForm()
        {
            EditFormPanel.Visible = false;
            GridViewPanel.Visible = true;
            ButtonPanel.Visible = true;
            LoadListCategory(String.Empty);
        }

        protected void BindGridView()
        {
            source = new List<HangObj>();
            source = HangDAL.GetByAllAdmin();
            HangGridView.DataSource = source;
            HangGridView.DataBind();
        }

        protected void LoadDonvitinh()
        {
            List<DonvitinhObj> list = DonvitinhDAL.GetByAll();
            cboDonvitinh.DataSource = list;
            cboDonvitinh.DataValueField = "DonvitinhID";
            cboDonvitinh.DataTextField = "Tendonvitinh";
            cboDonvitinh.DataBind();
        }

        protected void HangGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            HangID = e.CommandArgument.ToString();
            obj = new HangObj();
            obj = HangDAL.GetByID(HangID);
            switch (e.CommandName)
            {
                case CMD_EDIT:
                    FillValueToForm(obj);
                    btnSave.Text = UPDATE;
                    LoadListCategory(HangID);
                    TurnPanelOnOff();
                    break;
                case CMD_DELETE:
                    HangDAL.Delete(HangID);
                    DanhMucHangDAL.DeleteByHangID(HangID);
                    BindGridView();
                    break;
            }
        }

        protected void Update(HangObj input, bool IsPriceChanged)
        {
            if (IsPriceChanged)
            {
                HangDAL.UpdateWithPrice(input);
                return;
            }
            HangDAL.Update(input);
        }

        protected void FillValueToForm(HangObj obj)
        {
            txtTenhang.Text = obj.Tenhang;
            txtThongtinsoluoc.Text = obj.Thongtinsoluoc;
            txtThongtinchitiet.Content = obj.Thongtinchitiet;
            txtXuatxu.Text = obj.Xuatxu;
            txtThutu.Text = obj.Thutu;
            txtTitle.Text = obj.Title;
            txtKeyword.Text = obj.Keyword;
            txtDescription.Text = obj.Description;
            chkActive.Checked = Boolean.Parse(obj.Active);
            cboDonvitinh.SelectedValue = obj.DonvitinhID;
            Solanmua = obj.Solanmua;
            txtAnh.Text = obj.Anh;
            setSelectedIndexcboType();
            imgAnh.ImageUrl = obj.Anh;
            txtGiabanle.Value = Convert.ToDouble(obj.Giabanle);
            txtGiathitruong.Value = Convert.ToDouble(obj.Giathitruong);
            txtGiabanbuon.Value = Convert.ToDouble(obj.Giabanbuon);
            giabanbuon = (double)txtGiabanbuon.Value;
            giabanle = (double)txtGiabanle.Value;
            giathitruong = (double)txtGiathitruong.Value;
            if (!String.IsNullOrEmpty(obj.Anh))
            {
                imgAnh.ImageUrl = obj.Anh;
            }
        }

        protected void SetValueFromForm()
        {
            if (obj == null)
                obj = new HangObj();
            obj.Tenhang = txtTenhang.Text;
            obj.Xuatxu = txtXuatxu.Text;
            obj.Thutu = txtThutu.Text;
            obj.DonvitinhID = cboDonvitinh.SelectedValue;
            obj.Title = txtTitle.Text;
            obj.Keyword = txtKeyword.Text;
            obj.Description = txtDescription.Text;
            obj.Active = Convert.ToString(chkActive.Checked);
            obj.Thongtinsoluoc = txtThongtinsoluoc.Text;
            obj.Thongtinchitiet = txtThongtinchitiet.Content;
            obj.Solanmua = Solanmua;
            obj.Url = StringHelper.NameToUrl(obj.Tenhang);
            obj.Anh = txtAnh.Text;
            obj.Giabanbuon = Convert.ToString(txtGiabanbuon.Value);
            obj.Giabanle = Convert.ToString(txtGiabanle.Value);
            obj.Giathitruong = Convert.ToString(txtGiathitruong.Value);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SetValueFromForm();
                switch (btnSave.Text)
                {
                    case UPDATE:
                        Update(obj, this.IsPriceChanged());
                        DanhMucHangDAL.DeleteByHangID(HangID);
                        InsertToDanhMucHang(obj);
                        BindGridView();
                        break;
                    case INSERT:
                        int id = HangDAL.Insert(obj);
                        obj.HangID = id.ToString();
                        InsertToDanhMucHang(obj);
                        BindGridView();
                        break;
                }
                ControlHelper.ResetControl(EditFormPanel);
                TurnPanelOnOff();
                obj = null;
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void HangGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            HangGridView.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            TurnPanelOnOff();
            ControlHelper.ResetControl(EditFormPanel);
            Response.Redirect(Request.RawUrl);
        }

        protected bool IsPriceChanged()
        {
            double mGiabanle = (double)txtGiabanle.Value;
            double mGiabanbuon = (double)txtGiabanbuon.Value;
            double mGiathitruong = (double)txtGiathitruong.Value;
            bool result = ((mGiabanle != giabanle) || (mGiabanbuon != giabanbuon) || (mGiathitruong != giathitruong));
            return result;
        }

        protected void TurnPanelOnOff()
        {
            GridViewPanel.Visible = !GridViewPanel.Visible;
            EditFormPanel.Visible = !EditFormPanel.Visible;
            ButtonPanel.Visible = !ButtonPanel.Visible;
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            TurnPanelOnOff();
            btnSave.Text = INSERT;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < HangGridView.Rows.Count; i++)
            {
                GridViewRow row = HangGridView.Rows[i];
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                    if (chk.Checked)
                    {
                        string ID = row.Cells[1].Text;
                        HangDAL.Delete(ID);
                        DanhMucHangDAL.DeleteByHangID(ID);
                    }
                }
            }
            HangGridView.PageIndex = 0;
            BindGridView();
        }

        protected void btnSubmitUpload_Click(object sender, EventArgs e)
        {
            if (uploader.UploadedFiles.Count > 0)
            {
                txtAnh.Text = "~/Upload/" + uploader.UploadedFiles[0].GetName();
                imgAnh.ImageUrl = txtAnh.Text;
                setSelectedIndexcboType();
            }
        }

        protected void setSelectedIndexcboType()
        {
            string url = txtAnh.Text;
            if (url.StartsWith("~"))
            {
                cboType.SelectedIndex = 1;
            }
            else
                cboType.SelectedIndex = 0;
        }

        protected void LoadListCategory(string HangID)
        {
            categories = new List<DanhmucObj>();
            categories = DanhmucDAL.GetByAll();
            List<DanhMucHangObj> selectedID = DanhMucHangDAL.GetByHangID(HangID);
            listCategory.DataSource = categories;
            listCategory.DataValueField = "DanhmucID";
            listCategory.DataTextField = "Tendanhmuc";
            listCategory.DataBind();
            if (!String.IsNullOrEmpty(HangID))
            {
                for (int i = 0; i < categories.Count; i++)
                {
                    for (int j = 0; j < selectedID.Count; j++)
                    {
                        if (listCategory.Items[i].Value == selectedID[j].DanhmucID)
                            listCategory.Items[i].Checked = true;
                    }
                }
            }
        }

        protected void InsertToDanhMucHang(HangObj obj)
        {
            for (int i = 0; i < listCategory.CheckedItems.Count; i++)
            {
                DanhMucHangObj tmp = new DanhMucHangObj();
                tmp.HangID = obj.HangID;
                tmp.DanhmucID = listCategory.CheckedItems[i].Value;
                DanhMucHangDAL.Insert(tmp);
            }
        }
    }
}